<template>
  <div class="dashboard-container">
    <div class="container">
      <div class="tableBar">
        
        <div class="serch">
          <label style="margin-right: 5px">商品名称：</label>
          <el-input
          v-model="input"
          placeholder="请输入商品名称"
          style="width: 20%;margin-right: 5px"
          clearable
          @clear="init"
          @keyup.enter.native="init()"
        />
        <el-button class="normal-btn continue" style="margin-right: 5px;height:40px" @click="init()"
          >查询</el-button
        >

        <label style="margin-right: 5px">商品状态：</label>
        <el-select v-model="status" slot="status" placeholder="请选择"  style="width: 10%;margin-right: 5px">
          <el-option label="禁用" :value="1"></el-option>
          <el-option label="启用" :value="0"></el-option>
          <el-option label="已过期" :value="2"></el-option>
          <el-option label="无" value=""></el-option>
        </el-select>

        <label style="margin-right: 5px">商品数量：</label>
        <el-input  v-model.number="productNum" placeholder="商品数量"  style="width: 10%;margin-right: 5px"></el-input>

        <label style="margin-right: 5px">保质期：</label>
        <el-input  v-model.number="shelfLife" placeholder="保质期/天"  style="width: 10%;margin-right: 5px"></el-input>

        
        </div>

        <el-button type="danger" class="delete" @click="deleteProducts()"> - 删除选中</el-button>
        
        <el-button
          type="primary"
          class="add"
          @click="addEmployeeHandle('add')"
        >
          + 添加库存
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        element-loading-text="拼命加载中"
        :data="tableData"
        stripe
        v-if="tableData.length"
        class="tableBox"
        style="line-height: 40px;"
        @selection-change="handleSelectionChange"
        @select='onSelect'
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column prop="name" label="名称"  show-overflow-tooltip/>
        <el-table-column prop="image" label="商品图片"  >
          <template slot-scope="scope">
            <img :src="scope.row.image" :alt="scope.row.name" style="height: 40px;"  v-image-preview>
          </template>
          <!-- <img :src="image" :alt="name"> -->
        </el-table-column>
        <el-table-column prop="productNum" label="库存数量"/>
        <el-table-column prop="price" label="价格"  >
          <template slot-scope="scope">
              {{ scope.row.price }}  ￥
          </template>
        </el-table-column>
        <el-table-column prop="shelfLife" label="保质期/天" >
          <template slot-scope="scope">
              {{ scope.row.shelfLife }}  
          </template>
          </el-table-column>
        <el-table-column label="状态" >
          <template slot-scope="scope" >
            <div
              class="tableColumn-status"
              :class="{ 'stop-use': String(scope.row.status) === '0' }"
            >
              {{ getStatus(scope.row.status) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="dateOfManufacture" label="生产日期"  width="160" />
        <el-table-column label="操作" width="160" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              class="blueBug"
              :class="{ 'disabled-text': scope.row.username === 'admin' }"
              :disabled="scope.row.username === 'admin'"
              @click="addEmployeeHandle('update',scope.row.id,scope.row.name,scope.row.categoryId)"
            >
              修改
            </el-button>
            <el-button
              :disabled="scope.row.username === 'admin'"
              type="text"
              size="small"
              class="non"
              :class="{
                'disabled-text': scope.row.username === 'admin',
                blueBug: scope.row.status == '0',
                delBut: scope.row.status != '0',
              }"
              @click="statusHandle(scope.row)"
            >
              {{ scope.row.status == '1' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="text"
              size="small"
              class="blueBug"
              style="color: red;"
              @click="deleteProduct(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Empty v-else :is-search="isSearch" />
      <el-pagination
        class="pageList"
        :page-sizes="[10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="counts"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import {inventoryPage2,inventoryStatus,deletes} from '@/api/inventory'
// import {categoryPage} from '@/api/category'
import Empty from '@/components/Empty/index.vue'

export default {
  components:{
    Empty
  },
  data() {
    return {
      loading: false,
      tableData:[],
      types:[],
      type:'',
      page:1,
      pageSize:10,
      input:'',
      isSearch:false,
      id:'',
      status:'',
      storeId:this.$store.state.user.userInfo.storeId,
      productNum:'',
      shelfLife:'',
      counts:0,
      initFun:'',
      date:'',
      multipleSelection: [],
      deleteIds:[]
    }
  },
  created(){
    this.init()
  },
  methods:{
    init(){
      const res = inventoryPage2(this.date,this.page,this.pageSize,this.input,this.productNum,this.shelfLife,this.storeId,this.status);
      res.then((res)=>{
        this.tableData = res.data.records
        this.counts = res.data.total
      }).catch((err)=>{
        console.log(err)
      })
    },

    addEmployeeHandle(methos,id,name,categoryId){
      this.$router.push({
        path:'/home/addInventory',
        query:{
          methods:methos,
          id:id,
          name:name,
          categoryId:categoryId
        }
      })
    },
   handleSizeChange(val) {
    this.pageSize = val
    this.init()
  },

   handleCurrentChange(val) {
    this.page = val
    this.init()
  },
  getType(id){
    return this.types.find(type=>type.id === id).name
  },
  statusHandle(value){
    let msg = value.status == 0 ? '启用':'禁用'

    if(value.status == 2){
      //时间转时间戳
      let timestamp = Date.parse(new Date(value.dateOfManufacture).toString());
      let newTime = timestamp + value.shelfLife * 24 * 60 * 60 * 1000
      let nowTime = Date.parse(new Date(new Date).toString())
      if(nowTime<newTime){
        msg = "启用已经过期的"
      }
      else{
        this.$message.error('启用失败，该商品已过期')
        return 
      }

    }
    this.$confirm('是否'+msg+'该商品？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          value.status = value.status == 0? 1: 0
          // console.log(value.status+','+value.id)
          const res = inventoryStatus(value.status,value.id)
          res.then((res)=>{
            // console.log(res)
            // value.status = value.status == 0? 1: 0
              this.$message({
              type: 'success',
              message: msg+'成功!'
            });
            this.init()
          }).catch((err)=>{
            this.$message.error(err)
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
  },
  getStatus(status){
    console.log(status)
    switch(status){
      case 0:
        return '禁用'
      case 1:
        return '启用'
      case 2:
        return '已过期'
      default:
        return '??'
    }
  },
  deleteProduct(ids){

    this.$confirm('是否删除商品？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          deletes(ids).then((res)=>{
            this.$message.success(res)
            //更新页面
            this.init()
          }).catch((err)=>{
            this.$message.error(err)
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });


  },
  deleteProducts(){
    // console.log(this.multipleSelection)
    if(this.multipleSelection != [] && this.multipleSelection.length != 0){

      this.$confirm('是否删除商品？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          let ids = []
          this.multipleSelection.forEach((product)=>{
            ids.push(product.id)
          })

          deletes(ids).then((res)=>{
            this.$message.success('删除成功')
            //更新页面
            this.init()

          }).catch((err)=>{
            this.$message.error(err)
          })

        }).catch(()=>{
          this.$message('已取消')
        })

    }
    else{

      this.$message({
            type: 'info',
            message: '选择商品为空'
          }); 
    }

  },

  //取消选择
  toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });

          console.log('if')
        } else {
          this.$refs.multipleTable.clearSelection();
          console.log('else')
        }
      },

  handleSelectionChange(val) {
        this.multipleSelection = val;
        // console.log(val)
        
  },
  onSelect(rows, row) {
    let selected = rows.includes(row);
    // console.log(rows)
    // console.log(row)
		// console.log(selected)  // true就是选中，0或者false是取消选中
    }
    
  }
}
</script>

<style  scoped>
.disabled-text {
  color: #bac0cd !important;
}
.tableBar{
  line-height: 40px;
  height: 70px;
  display: flex;
  justify-content: space-between;
}

.tableBox{
  height: 775px;
  border-radius: 5px;
  
}
.add{
  height: 40px;
  margin-right: 15px;
}

.delete{
  height: 40px;
  margin-left: 15px;
}

.pageList{
  line-height: 40px;
  margin-top: 15px;
}

.container{
  height: 88vh;
  
}

.serch{
  display: flex;
  height:  70px;
  justify-content: space-around;
}
</style>